<?php

class Block {

    private $oNode;

    public function __construct(DOMNode $oNode) {

        $this->oNode = $oNode;

    }

    public function process() {

        if(!$this->checkGuard($this->oNode)) {
            return "";
        }

        $sMethodClassName = "BlockMethod_" . ucwords($this->oNode->getAttribute("method"));

        try {
            class_exists($sMethodClassName);
        }
        catch(Exception $oException) {
            throw new Exception_BlockMethodNotFound($this->oNode->getAttribute("method"));
        }

        $oMethodInstance = new $sMethodClassName($this->processParams());

        return $oMethodInstance->run();

    }

    private function checkGuard() {

        $aNodeGuards = $this->oNode->getElementsByTagName("guard");

        foreach($aNodeGuards as $oNodeGuard) {
        	if(Value::create(
				$oNodeGuard->getAttribute("type"),
				Source::create($oNodeGuard->nodeValue, $oNodeGuard->getAttribute("source"))->get()
				)->isEmpty()
			) {
				return false;
			}
		}

		return true;

    }

    private function processParams() {

        $aResult = array();

        $aNodeParams = $this->oNode->getElementsByTagName("param");

        foreach($aNodeParams as $oNodeParam) {

            if(!$oNodeParam->hasAttribute("name")) {
                continue;
            }

            $aResult[$oNodeParam->getAttribute("name")] = Value::create(
				$oNodeParam->getAttribute("type"),
				Source::create($oNodeParam->nodeValue, $oNodeParam->getAttribute("source"))->get()
                );

        }

        return $aResult;

    }

}

?>